package com.bnz.order.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnz.common.entity.TbPayLog;
import com.bnz.common.utils.IdWorker;
import com.bnz.order.entity.Cart;
import com.bnz.order.entity.TbOrder;
import com.bnz.order.entity.TbOrderItem;
import com.bnz.order.mapper.TbOrderItemMapper;
import com.bnz.order.mapper.TbOrderMapper;
import com.bnz.order.mapper.TbPayLogMapper;
import com.bnz.order.service.OrderService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements OrderService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TbOrderItemMapper itemMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbPayLogMapper payLogMapper;

    //1. 根据登录名查询购物车列表
    @Override
    public List<Cart> getCartListByName(String name) {
        if (StringUtils.isNotBlank("name")) {
            String cartList = redisTemplate.opsForValue().get(name);
            System.out.println("cartList = " + cartList);
            return JSON.parseArray(cartList,Cart.class);
        }

        return null;
    }

    //2. 添加订单
    @Override
    public void addOrder(String name, TbOrder tbOrder) {
        //2.1 得到购物车列表 （一个购物车就是一个订单）
        List<Cart> cartList = getCartListByName(name);
        //定义订单总金额
        double total = 0;
        //定义订单id的列表
        List<String> ids = new ArrayList<>();
        //2.2 遍历购物车
        for (Cart cart : cartList) {
            //2.3 创建要添加的订单
            TbOrder order = new TbOrder();
            //2.3.1 为表单赋值
            //① 生成分布式id
            long orderId = idWorker.nextId();
            ids.add(orderId + "");
            order.setOrderId(orderId);
            order.setStatus("1");  //状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭,7、待评价
            order.setUserId(name);
            order.setSellerId(cart.getSellerId());
            order.setReceiver(tbOrder.getReceiver());
            order.setPaymentType(tbOrder.getPaymentType());
            order.setReceiverAreaName(tbOrder.getReceiverAreaName());
            order.setReceiverMobile(tbOrder.getReceiverMobile());
            order.setReceiver(tbOrder.getReceiver());
            order.setSourceType("2");      //订单来源：1:app端，2：pc端，3：M端，4：微信端，5：手机qq端
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            //定义某个订单的支付金额
            double sum = 0;
            //2.4 遍历购物项集合,添加订单项列表
            for (TbOrderItem item : cart.getOrderItemList()) {
                //2.4.1 构造要添加的订单项列表
                TbOrderItem orderItem = new TbOrderItem();
                //2.4.2 为订单项赋值
                orderItem.setItemId(item.getItemId());
                orderItem.setOrderId(orderId);
                orderItem.setTitle(item.getTitle());
                orderItem.setSellerId(item.getSellerId());
                orderItem.setPicPath(item.getPicPath());
                orderItem.setPrice(item.getPrice());
                orderItem.setNum(item.getNum());
                orderItem.setTotalFee(item.getTotalFee());
                orderItem.setId(idWorker.nextId());
                orderItem.setGoodsId(item.getGoodsId());
                //2.4.3 计算总金额
                sum += item.getTotalFee().doubleValue();
                //2.4.4 添加到数据库中
                itemMapper.insert(orderItem);
            }
            total += sum;
            //2.5 为订单总金额赋值
            order.setPayment(new BigDecimal(sum));           // 设置支付金额
            //2.6 将订单添加到数据库
            orderMapper.insert(order);


        }
        //2.7 添加支付日志
        //2.7.1 定义支付日志
        TbPayLog payLog = new TbPayLog();
        payLog.setCreateTime(new Date());
        payLog.setOutTradeNo(idWorker.nextId() + "");
        payLog.setPayType(tbOrder.getPaymentType());
        payLog.setTradeState("0");      //0: 未支付 1: 支付
        payLog.setTotalFee(new Double(total).longValue());       // 订单总金额
        payLog.setUserId(name);
        payLog.setOrderList(ids.toString().replace("[","").replace("]",""));
        //2.7.2 放到数据库中
        payLogMapper.insert(payLog);
        //2.7.3 将payLog放到redis中
        redisTemplate.opsForHash().put(name + "-pay","paylog",JSON.toJSONString(payLog));
        //2.8 从redis中删除购物车
        //todo...
    }
    //3. 从redis中得到支付日志
    @Override
    public TbPayLog getPayLogFromRedis(String name) {
        String paylog = (String) redisTemplate.opsForHash().get(name+"-pay", "paylog");
        return JSON.parseObject(paylog,TbPayLog.class);
    }
}